#include "net.h"

#include "..\logger\logger.h" // Logger class.

Net::Net()
{
	log->Msg("Initializing socket... ");

	if(WSAStartup(MAKEWORD(2, 2), &wsaData))
	{
		log->Error("Can't initialize socket.\n");
		WSACleanup();
		return;
	}

	s = INVALID_SOCKET;

	log->Msg("Socket initialized.\n");
}
Net::~Net()
{
	Disconnect();

	WSACleanup();
	log->Msg("Socket cleaned up.\n");
}

bool Net::Connect(const char *Hostname, const char* Port)
{
	log->Msg("Connecting to server... ");
	log->Msg(Hostname);
	log->Msg(" ");

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	if(getaddrinfo(Hostname, Port, &hints, &server))
	{
		log->Msg("Connecting failed! (getaddrinfo())\n");
		WSACleanup();
		return false;
	}

	s = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
	if(s == INVALID_SOCKET)
	{
		log->Msg("Connecting failed! (socket())\n");
		freeaddrinfo(server);
		WSACleanup();
		return false;
	}

	if(connect(s, server->ai_addr, (int)server->ai_addrlen) == SOCKET_ERROR)
	{
		log->Msg("Connecting failed! (connect())\n");
		closesocket(s);
		freeaddrinfo(server);
		WSACleanup();
		return false;
	}

	log->Msg("Connected successfully!\n");

	return true;
}

void Net::Disconnect()
{
	if(s != INVALID_SOCKET)
	{
		closesocket(s);
		log->Msg("Disconnected.\n");
	}
}

int Net::Send(const char *Data, int Length)
{
	int ret = send(s, Data, Length, 0);

	if(ret == SOCKET_ERROR)
		log->Msg("Sending failed.\n");

	return ret;
}

int Net::Recv(char *Buffer, int Length)
{
	int ret = recv(s, Buffer, Length, 0);

	if(ret == SOCKET_ERROR)
		log->Msg("Receiving failed.\n");
	
	return ret;
}